import React from 'react';
import { DatePicker } from 'antd';
import moment from 'moment';
import produce from 'immer';
import classNames from 'classnames';
import RangePicker from './RangePicker';
import MonthPicker from './MonthPicker';
import YearPicker from './YearPicker';
import AutoPicker from './AutoPicker';
import styles from './index.less';

const Index = (props) => {
  const {
    type, // 日期类型 => datetime, datetime-now, undefined

    showTime = false,
    format = 'YYYY-MM-DD',

    disabled,
    value,
    onChange,
    ...rest
  } = props;

  const { showTime: newShowTime, format: newFormat } = produce(
    { showTime, format },
    (draftState) => {
      if (type === 'datetime') {
        draftState.showTime = { defaultValue: moment('00:00:00', 'HH:mm:ss') };
        draftState.format = 'YYYY-MM-DD HH:mm:ss';
      }
      if (type === 'datetime-now') {
        draftState.showTime = true;
        draftState.format = 'YYYY-MM-DD HH:mm:ss';
      }
      return draftState;
    },
  );

  const newValue = value && moment(value, newFormat);

  if (!Object.keys(props).includes('value')) {
    return 'DEPRECATED';
  }

  if (disabled && disabled.render) {
    return (
      disabled.render(newValue?.format(newFormat), { value, format: newFormat }) || (
        <span>&nbsp;</span>
      )
    );
  }

  return (
    <span className={classNames(styles.col24, styles.componentWrapper)}>
      <DatePicker
        {...rest}
        disabled={!!disabled}
        showTime={newShowTime}
        format={newFormat}
        value={newValue}
        onChange={(date, dateString) => {
          if (onChange) {
            onChange(dateString || null);
          }
        }}
      />
    </span>
  );
};

Index.RangePicker = RangePicker;
Index.MonthPicker = MonthPicker;
Index.YearPicker = YearPicker;
Index.AutoPicker = AutoPicker;
Object.keys(DatePicker).forEach((item) => {
  if (!['defaultProps', 'propTypes', 'RangePicker', 'MonthPicker', 'YearPicker'].includes(item)) {
    Index[item] = DatePicker[item];
  }
});
Index.displayName = 'DatePicker';
export default Index;
